#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <cstring>
#include <cstdlib>

using namespace std;

void create_file() {
    char filename[256];
    cout << "请输入要创建的文件名: ";
    cin >> filename;
    int fd = open(filename, O_CREAT | O_EXCL | O_WRONLY, 0644);
    if (fd == -1) {
        perror("创建文件失败");
    } else {
        cout << "文件创建成功: " << filename << endl;
        close(fd);
    }
}

void write_file() {
    char filename[256];
    cout << "请输入要写入的文件名: ";
    cin >> filename;
    int fd = open(filename, O_WRONLY | O_APPEND);
    if (fd == -1) {
        perror("打开文件失败");
        return;
    }
    cout << "请输入要写入的内容(以#结束): ";
    string content, line;
    while (getline(cin, line)) {
        if (line.find('#') != string::npos) {
            content += line.substr(0, line.find('#'));
            break;
        }
        content += line + "\n";
    }
    ssize_t n = write(fd, content.c_str(), content.size());
    if (n == -1) perror("写入失败");
    else cout << "写入成功！" << endl;
    close(fd);
}

void read_file() {
    char filename[256];
    cout << "请输入要读取的文件名: ";
    cin >> filename;
    int fd = open(filename, O_RDONLY);
    if (fd == -1) {
        perror("打开文件失败");
        return;
    }
    char buf[1024];
    ssize_t n;
    cout << "文件内容如下：" << endl;
    while ((n = read(fd, buf, sizeof(buf)-1)) > 0) {
        buf[n] = '\0';
        cout << buf;
    }
    close(fd);
}

void change_permission() {
    char filename[256];
    int mode;
    cout << "请输入要修改权限的文件名: ";
    cin >> filename;
    cout << "请输入新的权限(八进制,如644): ";
    cin >> oct >> mode;
    if (chmod(filename, mode) == -1) {
        perror("修改权限失败");
    } else {
        cout << "权限修改成功！" << endl;
    }
}

void show_permission() {
    char filename[256];
    cout << "请输入要查看权限的文件名: ";
    cin >> filename;
    char* pargv[4] = {(char*)"ls", (char*)"-l", filename, NULL};
    if (fork() == 0) {
        execv("/bin/ls", pargv);
        exit(0);
    } else {
        wait(NULL);
    }
}

int main() {
    while (true) {
        cout << "\n文件工具 filetools\n";
        cout << "1. 创建新文件\n";
        cout << "2. 写文件\n";
        cout << "3. 读文件\n";
        cout << "4. 修改文件权限\n";
        cout << "5. 查看当前文件权限\n";
        cout << "0. 退出\n";
        cout << "请选择功能号: ";
        int choice;
        cin >> choice;
        cin.ignore(); // 清除输入缓冲区
        switch (choice) {
            case 1: create_file(); break;
            case 2: write_file(); break;
            case 3: read_file(); break;
            case 4: change_permission(); break;
            case 5: show_permission(); break;
            case 0: return 0;
            default: cout << "无效选择，请重新输入！" << endl;
        }
    }
}